package com.keyinong.qudan.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.app.Notification;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.SpeechUtility;
import com.keyinong.qudan.R;
import com.keyinong.qudan.tools.SpeechApp;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

public class App extends Application {
	public static String scan_pic_dir;
	public static List<LogEntity> rs = new ArrayList<LogEntity>();
	public static SharedPreferences sp;
	public static Editor editor;
	public static Gson gson;
	private PushAgent mPushAgent;

	@Override
	public void onCreate() {
		super.onCreate();
		scan_pic_dir = getResources().getString(R.string.scan_pic_dir);
		createTempDir();
		gson = new Gson();
		sp = getSharedPreferences("qrdata", MODE_PRIVATE);
		editor = sp.edit();

		readFromSp();
		SpeechUtility.createUtility(App.this, "appid=582428f2");
		
		mPushAgent = PushAgent.getInstance(App.this);
		mPushAgent.setDebugMode(true);
		
		UmengMessageHandler messageHandler = new UmengMessageHandler(){
			/**
			 * 参考集成文档的1.6.3
			 * http://dev.umeng.com/push/android/integration#1_6_3
			 * */
			@Override
			public void dealWithCustomMessage(final Context context, final UMessage msg) {
				new Handler().post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						// 对自定义消息的处理方式，点击或者忽略
						Log.i("zq", ""+msg);
						boolean isClickOrDismissed = true;
						if(isClickOrDismissed) {
							//自定义消息的点击统计
							UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
						} else {
							//自定义消息的忽略统计
							UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
					}
				});
			}
			
			/**
			 * 参考集成文档的1.6.4
			 * http://dev.umeng.com/push/android/integration#1_6_4
			 * */
//			@Override
//			public Notification getNotification(Context context,
//					UMessage msg) {
//				switch (msg.builder_id) {
//				case 1:
//					NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//					RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
//					myNotificationView.setTextViewText(R.id.notification_title, msg.title);
//					myNotificationView.setTextViewText(R.id.notification_text, msg.text);
//					myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
//					myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
//					builder.setContent(myNotificationView)
//                           .setSmallIcon(getSmallIconId(context, msg))
//					       .setTicker(msg.ticker)
//					       .setAutoCancel(true);
//
//					return builder.build();
//
//				default:
//					//默认为0，若填写的builder_id并不存在，也使用默认。
//					return super.getNotification(context, msg);
//				}
//			}
		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * 该Handler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
		 * 参考集成文档的1.6.2
		 * http://dev.umeng.com/push/android/integration#1_6_2
		 * */
		UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler(){
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {
				Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
			}
		};
		//使用自定义的NotificationHandler，来结合友盟统计处理消息通知
		//参考http://bbs.umeng.com/thread-11112-1-1.html
		//CustomNotificationHandler notificationClickHandler = new CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);
		
//		if (MiPushRegistar.checkDevice(this)) {
//            MiPushRegistar.register(this, "2882303761517400865", "5501740053865");
//		}
	
	}

	/**
	 * 
	 * 此方法描述的是：向sp中写入数�?	 * 
	 * @author: limengwei
	 * @version: 2014-7-1 下午4:19:40
	 */
	public static void witeToSp() {
		editor.putString("logdata", gson.toJson(rs));
		editor.commit();
	}

	/**
	 * 
	 * 此方法描述的是：从sp中读取数�?	 * 
	 * @author: limengwei
	 * @version: 2014-7-1 下午4:20:01
	 */
	public void readFromSp() {
		Type type = new TypeToken<List<LogEntity>>() {
		}.getType();
		List<LogEntity> list = gson.fromJson(sp.getString("logdata", ""), type);
		if (list != null) {
			rs.clear();
			rs.addAll(list);
		}
	}

	/**
	 * 
	 * 此方法描述的是：创建缓存文件�?	 * 
	 * @author: limengwei
	 * @version: 2014-7-1 上午8:51:25
	 */
	public void createTempDir() {
		File dir = new File(scan_pic_dir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		scan_pic_dir = dir.getPath();
	}

	/**
	 * 
	 * 此方法描述的是： 保存Bitmap到SD�?	 * 
	 * @author: limengwei
	 * @version: 2014-7-1 上午8:53:51
	 */
	public static String saveBitmap(Bitmap bitmap) {

		File file = new File(App.scan_pic_dir, "scan_pic_" + System.currentTimeMillis() + ".png");
		FileOutputStream out;
		try {
			out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
				return file.getPath();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	/**
	 * 
	 * 此方法描述的是： 复制内容到剪贴板
	 * 
	 * @author: limengwei
	 * @version: 2014-7-1 上午9:19:50
	 */
	@SuppressWarnings("deprecation")
	public static void copy(String content, Context context) {
		ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(content.trim());
		Toast.makeText(context, "已复制到剪贴", Toast.LENGTH_SHORT).show();
	}

}
